import gradio as gr
import os
import base64
import requests
from openai import OpenAI
import json
import uvicorn
from fastapi import FastAPI, HTTPException, UploadFile, File
from pydantic import BaseModel
from typing import Optional, List

# --- 配置部分 ---
BAIDU_API_KEY = os.environ.get("BAIDU_API_KEY", "xxx")  # 替换为您的实际API Key
BAIDU_BASE_URL = "https://aistudio.baidu.com/llm/lmapi/v3"
MODEL_NAME = "ernie-4.5-turbo-vl"  # 百度多模态模型

# 初始化百度AI客户端（兼容OpenAI格式）
client = OpenAI(
    api_key=BAIDU_API_KEY,
    base_url=BAIDU_BASE_URL,
)

# 产品数据库 (示例数据)
FORXEE_PRODUCTS = {
    "榨汁设备": [
        {
            "型号": "FX-ZZ-1000",
            "产能": "1-2吨/小时",
            "适用原料": "苹果、梨、橙子等常见水果",
            "特点": "高效榨汁，汁渣分离彻底",
        },
        {
            "型号": "FX-ZZ-3000",
            "产能": "3-5吨/小时",
            "适用原料": "各类水果及部分蔬菜",
            "特点": "大型生产线专用，自动化程度高",
        },
        {
            "型号": "FX-ZZ-500",
            "产能": "0.5吨/小时以下",
            "适用原料": "浆果类如草莓、蓝莓等",
            "特点": "专为小型加工厂设计，操作简便",
        },
    ],
    "杀菌设备": [
        {
            "型号": "FX-SJ-2000",
            "处理量": "2-4吨/小时",
            "杀菌方式": "超高温瞬时杀菌",
            "适用产品": "澄清汁、浓缩汁",
        },
        {
            "型号": "FX-SJ-5000",
            "处理量": "5-8吨/小时",
            "杀菌方式": "巴氏杀菌",
            "适用产品": "浑浊汁、带果肉果汁",
        },
    ],
    "灌装设备": [
        {
            "型号": "FX-GZ-1000",
            "速度": "1000瓶/小时",
            "适用容器": "PET瓶、玻璃瓶",
            "特点": "多功能灌装，适应多种规格",
        },
        {
            "型号": "FX-GZ-3000",
            "速度": "3000瓶/小时",
            "适用容器": "PET瓶",
            "特点": "高速生产线专用",
        },
    ],
    "预处理设备": [
        {
            "型号": "FX-YC-1000",
            "功能": "清洗、去皮、去核",
            "适用原料": "苹果、梨等硬果类",
            "特点": "自动化处理，节省人工",
        },
        {
            "型号": "FX-YC-2000",
            "功能": "清洗、破碎",
            "适用原料": "浆果类、蔬菜类",
            "特点": "柔和处理，减少原料损伤",
        },
    ],
}


# --- 工具函数 ---
def encode_image(image_path):
    """将图片编码为base64格式"""
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")


def get_product_recommendations(capacity, raw_materials, product_type):
    """根据用户需求推荐合适的设备"""
    recommendations = []

    # 推荐榨汁设备
    for product in FORXEE_PRODUCTS["榨汁设备"]:
        # 简单匹配逻辑，实际应用中可更复杂
        capacity_match = (
            (capacity <= 0.5 and product["产能"].startswith("0.5"))
            or (0.5 < capacity <= 2 and product["产能"].startswith("1-2"))
            or (capacity > 2 and product["产能"].startswith("3-5"))
        )

        material_match = any(mat in product["适用原料"] for mat in raw_materials)

        if capacity_match and material_match:
            recommendations.append(
                {
                    "类型": "榨汁设备",
                    "型号": product["型号"],
                    "推荐理由": f"产能匹配({product['产能']})，适用于{product['适用原料']}，{product['特点']}",
                }
            )

    # 根据产品类型推荐杀菌设备
    if product_type in ["澄清汁", "浓缩汁"]:
        sterilization_equipment = next(
            (p for p in FORXEE_PRODUCTS["杀菌设备"] if "超高温" in p["杀菌方式"]), None
        )
    else:
        sterilization_equipment = next(
            (p for p in FORXEE_PRODUCTS["杀菌设备"] if "巴氏" in p["杀菌方式"]), None
        )

    if sterilization_equipment:
        recommendations.append(
            {
                "类型": "杀菌设备",
                "型号": sterilization_equipment["型号"],
                "推荐理由": f"适用于{sterilization_equipment['适用产品']}，采用{sterilization_equipment['杀菌方式']}，处理量{sterilization_equipment['处理量']}",
            }
        )

    # 推荐灌装设备
    filling_speed = "1000瓶/小时" if capacity <= 2 else "3000瓶/小时"
    filling设备 = next(
        (p for p in FORXEE_PRODUCTS["灌装设备"] if p["速度"] == filling_speed), None
    )
    if filling设备:
        recommendations.append(
            {
                "类型": "灌装设备",
                "型号": filling设备["型号"],
                "推荐理由": f"灌装速度{filling设备['速度']}，适用{filling设备['适用容器']}，{filling设备['特点']}",
            }
        )

    # 推荐预处理设备
    pre设备 = (
        FORXEE_PRODUCTS["预处理设备"][0]
        if any(mat in ["苹果", "梨"] for mat in raw_materials)
        else FORXEE_PRODUCTS["预处理设备"][1]
    )
    recommendations.append(
        {
            "类型": "预处理设备",
            "型号": pre设备["型号"],
            "推荐理由": f"适用于{pre设备['适用原料']}，可进行{pre设备['功能']}，{pre设备['特点']}",
        }
    )

    return recommendations


# --- 核心处理函数 ---
def analyze_raw_material_core(raw_material, image_data=None):
    """分析原料特性"""
    messages = [
        {
            "role": "system",
            "content": "你是一位果蔬加工领域的专家，擅长分析各类果蔬原料的加工特性和适用性。",
        },
        {
            "role": "user",
            "content": f"""
        请分析以下果蔬原料的加工特性：
        原料名称：{raw_material}
        
        请提供以下信息：
        1. 该原料的主要成分和营养价值
        2. 适合的榨汁工艺和注意事项
        3. 加工过程中可能遇到的问题及解决方案
        4. 该原料与其他原料的搭配建议
        5. 加工后的产品保质期和储存建议
        """,
        },
    ]

    # 如果有图片，添加图片信息
    if image_data:
        messages[1]["content"] += "\n请结合提供的原料图片进行更准确的分析。"
        messages[1]["content"] = [
            {"type": "text", "text": messages[1]["content"]},
            {
                "type": "image_url",
                "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},
            },
        ]

    try:
        completion = client.chat.completions.create(
            model=MODEL_NAME,
            messages=messages,
            stream=False,
            temperature=0.6,
        )

        ai_response = completion.choices[0].message.content
        return {"success": True, "result": ai_response}
    except Exception as e:
        print(f"调用AI API时出错: {e}")
        return {"success": False, "error": f"分析失败：{str(e)}"}


def recommend_equipment_core(capacity, raw_materials, product_type, production_scale):
    """推荐设备和生产线配置"""
    # 获取产品推荐
    product_recs = get_product_recommendations(capacity, raw_materials, product_type)

    # 构建提示词
    prompt = f"""
    请根据以下信息，为客户推荐合适的果蔬汁加工生产线配置方案：
    
    客户需求：
    - 预计产能：{capacity}吨/小时
    - 原料种类：{', '.join(raw_materials)}
    - 产品类型：{product_type}
    - 生产规模：{production_scale}
    
    已初步筛选的设备推荐：
    {json.dumps(product_recs, ensure_ascii=False, indent=2)}
    
    请提供：
    1. 完整的生产线配置方案，包括设备清单、布局建议
    2. 设备配置的详细理由，如何满足客户的产能和产品需求
    3. 预估的生产线投资成本范围和占地面积
    4. 生产效率和能耗分析
    5. 生产线的优势和可能的优化方向
    6. 设备安装和调试的时间周期
    """

    try:
        completion = client.chat.completions.create(
            model=MODEL_NAME,
            messages=[
                {
                    "role": "system",
                    "content": "你是一位果蔬汁加工设备和生产线配置专家，熟悉福各类设备特性和应用场景。",
                },
                {"role": "user", "content": prompt},
            ],
            stream=False,
            temperature=0.5,
        )

        ai_response = completion.choices[0].message.content
        # 添加设备详情到响应中
        return {
            "success": True,
            "result": ai_response,
            "equipment_details": product_recs,
        }
    except Exception as e:
        print(f"调用AI API时出错: {e}")
        return {"success": False, "error": f"推荐失败：{str(e)}"}


def optimize_process_core(
    raw_materials, product_type, current_issues, production_data=None
):
    """工艺优化建议"""
    prompt = f"""
    请根据以下信息，为客户提供果蔬汁加工工艺的优化建议：
    
    生产信息：
    - 原料种类：{', '.join(raw_materials)}
    - 产品类型：{product_type}
    - 当前存在的问题：{current_issues if current_issues else '无明确问题，寻求工艺优化'}
    {f'- 生产数据：{production_data}' if production_data else ''}
    
    请提供：
    1. 针对当前问题的具体解决方案
    2. 原料预处理的优化建议
    3. 榨汁/提取工艺的参数优化
    4. 杀菌和保鲜工艺的改进方案
    5. 可能提高产品质量和产量的创新工艺
    6. 生产过程中的能耗和成本优化建议
    7. 工艺改进的预期效果和投资回报分析
    """

    try:
        completion = client.chat.completions.create(
            model=MODEL_NAME,
            messages=[
                {
                    "role": "system",
                    "content": "你是一位果蔬汁加工工艺专家，擅长解决生产中的技术难题和优化生产流程。",
                },
                {"role": "user", "content": prompt},
            ],
            stream=False,
            temperature=0.6,
        )

        ai_response = completion.choices[0].message.content
        return {"success": True, "result": ai_response}
    except Exception as e:
        print(f"调用AI API时出错: {e}")
        return {"success": False, "error": f"工艺优化分析失败：{str(e)}"}


def diagnose_fault_core(equipment_type, fault_description, image_data=None):
    """设备故障诊断"""
    messages = [
        {
            "role": "system",
            "content": "你是一位果蔬汁加工设备维修专家，擅长诊断和解决各类设备故障。",
        },
        {
            "role": "user",
            "content": f"""
        请诊断以下设备故障并提供解决方案：
        
        设备类型：{equipment_type}
        故障描述：{fault_description}
        
        请提供：
        1. 可能的故障原因分析
        2. 详细的故障排查步骤
        3. 维修解决方案和所需工具
        4. 预防类似故障的建议
        5. 如果需要更换零件，建议的备件型号和规格
        6. 维修后的测试方法
        """,
        },
    ]

    # 如果有图片，添加图片信息
    if image_data:
        messages[1]["content"] += "\n请结合提供的故障部位图片进行更准确的诊断。"
        messages[1]["content"] = [
            {"type": "text", "text": messages[1]["content"]},
            {
                "type": "image_url",
                "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},
            },
        ]

    try:
        completion = client.chat.completions.create(
            model=MODEL_NAME,
            messages=messages,
            stream=False,
            temperature=0.5,
        )

        ai_response = completion.choices[0].message.content
        return {"success": True, "result": ai_response}
    except Exception as e:
        print(f"调用AI API时出错: {e}")
        return {"success": False, "error": f"故障诊断失败：{str(e)}"}


def recommend_formula_core(
    raw_materials, target_flavor, nutritional_goals, market_position
):
    """配方推荐"""
    prompt = f"""
    请根据以下信息，为客户推荐合适的果蔬汁配方：
    
    可用原料：{', '.join(raw_materials)}
    目标风味：{target_flavor}
    营养目标：{nutritional_goals}
    市场定位：{market_position}
    
    请提供：
    1. 详细的原料配比和用量
    2. 配方的独特卖点和优势
    3. 生产工艺要点和注意事项
    4. 产品的营养价值分析
    5. 可能的包装建议和保质期
    6. 目标消费群体和市场前景分析
    7. 与同类产品的竞争优势
    """

    try:
        completion = client.chat.completions.create(
            model=MODEL_NAME,
            messages=[
                {
                    "role": "system",
                    "content": "你是一位果蔬汁配方研发专家，熟悉各类果蔬的搭配和市场趋势。",
                },
                {"role": "user", "content": prompt},
            ],
            stream=False,
            temperature=0.7,
        )

        ai_response = completion.choices[0].message.content
        return {"success": True, "result": ai_response}
    except Exception as e:
        print(f"调用AI API时出错: {e}")
        return {"success": False, "error": f"配方推荐失败：{str(e)}"}


def market_analysis_core(product_type, target_region, market_trends=None):
    """市场分析"""
    prompt = f"""
    请根据以下信息，提供果蔬汁产品的市场分析：
    
    产品类型：{product_type}
    目标市场：{target_region}
    {f'已知市场趋势：{market_trends}' if market_trends else ''}
    
    请提供：
    1. 当前市场规模和增长预测
    2. 主要竞争对手和市场份额
    3. 消费者偏好和购买行为分析
    4. 价格区间和利润空间分析
    5. 潜在的市场机会和风险
    6. 有效的市场营销策略建议
    7. 产品创新方向和发展趋势
    """

    try:
        completion = client.chat.completions.create(
            model=MODEL_NAME,
            messages=[
                {
                    "role": "system",
                    "content": "你是一位食品饮料行业的市场分析专家，熟悉果蔬汁市场的趋势和消费者需求。",
                },
                {"role": "user", "content": prompt},
            ],
            stream=False,
            temperature=0.6,
        )

        ai_response = completion.choices[0].message.content
        return {"success": True, "result": ai_response}
    except Exception as e:
        print(f"调用AI API时出错: {e}")
        return {"success": False, "error": f"市场分析失败：{str(e)}"}


# --- Gradio界面包装函数 ---
def analyze_raw_material(raw_material, image):
    """原料分析Gradio包装函数"""
    image_data = None
    if image is not None:
        # 保存图片并编码
        temp_path = "temp_raw_material.jpg"
        image.save(temp_path)
        image_data = encode_image(temp_path)
        os.remove(temp_path)  # 清理临时文件

    result_dict = analyze_raw_material_core(raw_material, image_data)
    if result_dict["success"]:
        return result_dict["result"]
    else:
        return f"分析失败：{result_dict['error']}"


def recommend_equipment(capacity, raw_materials, product_type, production_scale):
    """设备推荐Gradio包装函数"""
    # 将逗号分隔的原料转换为列表
    raw_materials_list = [
        mat.strip() for mat in raw_materials.split(",") if mat.strip()
    ]
    result_dict = recommend_equipment_core(
        float(capacity), raw_materials_list, product_type, production_scale
    )
    if result_dict["success"]:
        return result_dict["result"]
    else:
        return f"推荐失败：{result_dict['error']}"


def optimize_process(raw_materials, product_type, current_issues, production_data):
    """工艺优化Gradio包装函数"""
    raw_materials_list = [
        mat.strip() for mat in raw_materials.split(",") if mat.strip()
    ]
    result_dict = optimize_process_core(
        raw_materials_list, product_type, current_issues, production_data
    )
    if result_dict["success"]:
        return result_dict["result"]
    else:
        return f"工艺优化分析失败：{result_dict['error']}"


def diagnose_fault(equipment_type, fault_description, image):
    """故障诊断Gradio包装函数"""
    image_data = None
    if image is not None:
        # 保存图片并编码
        temp_path = "temp_fault.jpg"
        image.save(temp_path)
        image_data = encode_image(temp_path)
        os.remove(temp_path)  # 清理临时文件

    result_dict = diagnose_fault_core(equipment_type, fault_description, image_data)
    if result_dict["success"]:
        return result_dict["result"]
    else:
        return f"故障诊断失败：{result_dict['error']}"


def recommend_formula(raw_materials, target_flavor, nutritional_goals, market_position):
    """配方推荐Gradio包装函数"""
    raw_materials_list = [
        mat.strip() for mat in raw_materials.split(",") if mat.strip()
    ]
    result_dict = recommend_formula_core(
        raw_materials_list, target_flavor, nutritional_goals, market_position
    )
    if result_dict["success"]:
        return result_dict["result"]
    else:
        return f"配方推荐失败：{result_dict['error']}"


def market_analysis(product_type, target_region, market_trends):
    """市场分析Gradio包装函数"""
    result_dict = market_analysis_core(product_type, target_region, market_trends)
    if result_dict["success"]:
        return result_dict["result"]
    else:
        return f"市场分析失败：{result_dict['error']}"


# --- Gradio界面定义 ---
def gradio_interface():
    """创建Gradio界面"""
    with gr.Blocks(title="果智通 - 果蔬汁加工智能助手") as demo:
        gr.Markdown("## 🥤 果智通 - 果蔬汁加工智能助手")
        gr.Markdown(
            "专为果蔬汁加工企业提供全方位智能支持，基于优质设备与AI技术的完美结合"
        )

        # 导航标签
        with gr.Tabs():
            # 原料分析标签
            with gr.Tab("1. 原料分析"):
                gr.Markdown("### 原料特性分析")
                gr.Markdown("输入原料信息并上传图片，获取详细的加工特性分析")

                with gr.Row():
                    with gr.Column(scale=2):
                        raw_material = gr.Textbox(
                            label="原料名称",
                            placeholder="例如：苹果、胡萝卜、蓝莓",
                            value="苹果",
                        )
                        raw_material_image = gr.Image(
                            type="pil", label="原料图片", height=200
                        )
                        analyze_btn = gr.Button("分析原料特性", variant="primary")

                raw_material_output = gr.Markdown(label="原料分析结果")

                analyze_btn.click(
                    fn=analyze_raw_material,
                    inputs=[raw_material, raw_material_image],
                    outputs=raw_material_output,
                )

            # 设备推荐标签
            with gr.Tab("2. 设备推荐"):
                gr.Markdown("### 生产线设备推荐")
                gr.Markdown("根据您的生产需求，推荐最合适的设备配置方案")

                with gr.Row():
                    with gr.Column(scale=1):
                        capacity = gr.Number(label="预计产能 (吨/小时)", value=2.0)
                        product_type = gr.Dropdown(
                            label="产品类型",
                            choices=[
                                "澄清汁",
                                "浑浊汁",
                                "浓缩汁",
                                "带果肉果汁",
                                "混合果蔬汁",
                            ],
                            value="澄清汁",
                        )
                        production_scale = gr.Radio(
                            label="生产规模",
                            choices=["小型试产线", "中型生产线", "大型工业化生产线"],
                            value="中型生产线",
                        )

                with gr.Row():
                    with gr.Column(scale=2):
                        raw_materials = gr.Textbox(
                            label="原料种类",
                            placeholder="请输入原料，用逗号分隔",
                            value="苹果, 梨",
                        )
                        equip_recommend_btn = gr.Button(
                            "推荐设备配置", variant="primary"
                        )

                equipment_output = gr.Markdown(label="设备配置推荐结果")

                equip_recommend_btn.click(
                    fn=recommend_equipment,
                    inputs=[capacity, raw_materials, product_type, production_scale],
                    outputs=equipment_output,
                )

            # 工艺优化标签
            with gr.Tab("3. 工艺优化"):
                gr.Markdown("### 生产工艺优化")
                gr.Markdown("分析当前生产工艺，提供优化建议和问题解决方案")

                with gr.Row():
                    with gr.Column(scale=1):
                        process_raw_materials = gr.Textbox(
                            label="原料种类",
                            placeholder="请输入原料，用逗号分隔",
                            value="橙子",
                        )
                        process_product_type = gr.Dropdown(
                            label="产品类型",
                            choices=[
                                "澄清汁",
                                "浑浊汁",
                                "浓缩汁",
                                "带果肉果汁",
                                "混合果蔬汁",
                            ],
                            value="澄清汁",
                        )

                with gr.Row():
                    with gr.Column(scale=2):
                        current_issues = gr.Textbox(
                            label="当前存在的问题",
                            placeholder="例如：出汁率低、口感不佳、色泽不理想等",
                            value="出汁率低于行业平均水平",
                        )
                        production_data = gr.Textbox(
                            label="生产数据",
                            placeholder="例如：出汁率、糖度、酸度等数据",
                        )
                        optimize_btn = gr.Button("优化生产工艺", variant="primary")

                process_output = gr.Markdown(label="工艺优化建议")

                optimize_btn.click(
                    fn=optimize_process,
                    inputs=[
                        process_raw_materials,
                        process_product_type,
                        current_issues,
                        production_data,
                    ],
                    outputs=process_output,
                )

            # 故障诊断标签
            with gr.Tab("4. 故障诊断"):
                gr.Markdown("### 设备故障诊断")
                gr.Markdown("描述设备故障现象，上传图片，获取诊断和解决方案")

                with gr.Row():
                    with gr.Column(scale=1):
                        equipment_type = gr.Dropdown(
                            label="设备类型",
                            choices=[
                                "榨汁设备",
                                "杀菌设备",
                                "灌装设备",
                                "预处理设备",
                                "其他设备",
                            ],
                            value="榨汁设备",
                        )

                with gr.Row():
                    with gr.Column(scale=2):
                        fault_description = gr.Textbox(
                            label="故障描述",
                            placeholder="请详细描述设备故障现象",
                            value="设备运行时有异常噪音，出汁率下降",
                        )
                        fault_image = gr.Image(
                            type="pil", label="故障部位图片", height=200
                        )
                        diagnose_btn = gr.Button("诊断故障", variant="primary")

                fault_output = gr.Markdown(label="故障诊断结果")

                diagnose_btn.click(
                    fn=diagnose_fault,
                    inputs=[equipment_type, fault_description, fault_image],
                    outputs=fault_output,
                )

            # 配方推荐标签
            with gr.Tab("5. 配方推荐"):
                gr.Markdown("### 果蔬汁配方推荐")
                gr.Markdown("根据原料和市场需求，推荐最佳配方方案")

                with gr.Row():
                    with gr.Column(scale=1):
                        formula_raw_materials = gr.Textbox(
                            label="可用原料",
                            placeholder="请输入可用原料，用逗号分隔",
                            value="胡萝卜, 苹果, 橙",
                        )
                        target_flavor = gr.Dropdown(
                            label="目标风味",
                            choices=["清甜", "酸甜", "浓郁", "清爽", "醇厚"],
                            value="酸甜",
                        )

                with gr.Row():
                    with gr.Column(scale=2):
                        nutritional_goals = gr.Textbox(
                            label="营养目标",
                            placeholder="例如：高维生素C、低糖分、高纤维等",
                            value="高维生素C，均衡营养",
                        )
                        market_position = gr.Radio(
                            label="市场定位",
                            choices=["大众消费", "高端健康", "儿童专用", "功能性饮料"],
                            value="大众消费",
                        )
                        formula_btn = gr.Button("推荐配方", variant="primary")

                formula_output = gr.Markdown(label="配方推荐结果")

                formula_btn.click(
                    fn=recommend_formula,
                    inputs=[
                        formula_raw_materials,
                        target_flavor,
                        nutritional_goals,
                        market_position,
                    ],
                    outputs=formula_output,
                )

            # 市场分析标签
            with gr.Tab("6. 市场分析"):
                gr.Markdown("### 市场趋势分析")
                gr.Markdown("分析市场趋势，为产品定位和营销策略提供建议")

                with gr.Row():
                    with gr.Column(scale=1):
                        market_product_type = gr.Dropdown(
                            label="产品类型",
                            choices=[
                                "澄清汁",
                                "浑浊汁",
                                "浓缩汁",
                                "带果肉果汁",
                                "混合果蔬汁",
                                "功能性果蔬汁",
                            ],
                            value="混合果蔬汁",
                        )
                        target_region = gr.Dropdown(
                            label="目标市场",
                            choices=[
                                "国内市场",
                                "欧洲市场",
                                "北美市场",
                                "东南亚市场",
                                "全球市场",
                            ],
                            value="国内市场",
                        )

                with gr.Row():
                    with gr.Column(scale=2):
                        market_trends = gr.Textbox(
                            label="已知市场趋势 (可选)",
                            placeholder="例如：低糖、有机、功能性等趋势",
                        )
                        market_btn = gr.Button("分析市场", variant="primary")

                market_output = gr.Markdown(label="市场分析结果")

                market_btn.click(
                    fn=market_analysis,
                    inputs=[market_product_type, target_region, market_trends],
                    outputs=market_output,
                )

        gr.Markdown("---")
        gr.Markdown(
            """
        ### 关于果智通
        果智通是果蔬汁机械有限公司推出的AI智能助手，旨在为果蔬汁加工企业提供全方位的技术支持和决策参考。
        
        本工具提供的分析和建议仅供参考，具体生产决策请结合实际情况。
        """
        )

    return demo


# --- FastAPI 应用和 API 端点定义 ---

# 1. 创建 FastAPI 应用实例
app = FastAPI(
    title="果智通 - 果蔬汁加工智能助手",
    description="为果蔬汁加工企业提供全方位智能支持",
)


# 2. 定义请求体模型
class RawMaterialAnalysisRequest(BaseModel):
    raw_material: str
    image_data: Optional[str] = None  # base64编码的图片数据


class EquipmentRecommendationRequest(BaseModel):
    capacity: float
    raw_materials: List[str]
    product_type: str
    production_scale: str


class ProcessOptimizationRequest(BaseModel):
    raw_materials: List[str]
    product_type: str
    current_issues: str
    production_data: Optional[str] = None


class FaultDiagnosisRequest(BaseModel):
    equipment_type: str
    fault_description: str
    image_data: Optional[str] = None  # base64编码的图片数据


class FormulaRecommendationRequest(BaseModel):
    raw_materials: List[str]
    target_flavor: str
    nutritional_goals: str
    market_position: str


class MarketAnalysisRequest(BaseModel):
    product_type: str
    target_region: str
    market_trends: Optional[str] = None


# 3. 定义API端点
@app.post("/api/analyze-raw-material", summary="分析原料特性")
async def api_analyze_raw_material(request: RawMaterialAnalysisRequest):
    result = analyze_raw_material_core(request.raw_material, request.image_data)
    if result["success"]:
        return result
    else:
        raise HTTPException(status_code=500, detail=result["error"])


@app.post("/api/recommend-equipment", summary="推荐设备配置")
async def api_recommend_equipment(request: EquipmentRecommendationRequest):
    result = recommend_equipment_core(
        request.capacity,
        request.raw_materials,
        request.product_type,
        request.production_scale,
    )
    if result["success"]:
        return result
    else:
        raise HTTPException(status_code=500, detail=result["error"])


@app.post("/api/optimize-process", summary="优化生产工艺")
async def api_optimize_process(request: ProcessOptimizationRequest):
    result = optimize_process_core(
        request.raw_materials,
        request.product_type,
        request.current_issues,
        request.production_data,
    )
    if result["success"]:
        return result
    else:
        raise HTTPException(status_code=500, detail=result["error"])


@app.post("/api/diagnose-fault", summary="诊断设备故障")
async def api_diagnose_fault(request: FaultDiagnosisRequest):
    result = diagnose_fault_core(
        request.equipment_type, request.fault_description, request.image_data
    )
    if result["success"]:
        return result
    else:
        raise HTTPException(status_code=500, detail=result["error"])


@app.post("/api/recommend-formula", summary="推荐果蔬汁配方")
async def api_recommend_formula(request: FormulaRecommendationRequest):
    result = recommend_formula_core(
        request.raw_materials,
        request.target_flavor,
        request.nutritional_goals,
        request.market_position,
    )
    if result["success"]:
        return result
    else:
        raise HTTPException(status_code=500, detail=result["error"])


@app.post("/api/analyze-market", summary="分析市场趋势")
async def api_analyze_market(request: MarketAnalysisRequest):
    result = market_analysis_core(
        request.product_type, request.target_region, request.market_trends
    )
    if result["success"]:
        return result
    else:
        raise HTTPException(status_code=500, detail=result["error"])


# 处理图片上传的端点
@app.post("/api/upload-image", summary="上传图片并获取base64编码")
async def upload_image(file: UploadFile = File(...)):
    try:
        contents = await file.read()
        base64_str = base64.b64encode(contents).decode("utf-8")
        return {"success": True, "image_data": base64_str}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"图片处理失败：{str(e)}")


# 4. 健康检查端点
@app.get("/health", summary="健康检查")
async def health_check():
    return {"status": "healthy", "service": "果智通 - 果蔬汁加工智能助手"}


# --- 应用启动逻辑 ---
demo = gradio_interface()
app = gr.mount_gradio_app(app=app, blocks=demo, path="/")

if __name__ == "__main__":
    print("🚀 启动果智通AI应用...")
    print("📱 Gradio 界面访问地址: http://localhost:7860")
    print("💻 FastAPI 文档地址: http://localhost:7860/docs")
    print("-" * 50)

    uvicorn.run(app, host="0.0.0.0", port=7860)
